/*
Designer   : Renyangang

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package device

import (
	"context"
	"fpga-vboard/pins"
)

const (
	CLOCK_SIG_NAME = "clk"
	RESET_SIG_NAME = "rst"
)

func init() {
	config := &SocGlobalConfig{
		DeviceInfo: DeviceInfo{
			Id:        SOC_GLOBAL_DEFAULT,
			Type:      SOC_GLOBAL,
			Name:      "soc_global",
			InputPins: nil,
			OutputPins: []*pins.PinDef{
				pins.NewPinDef(CLOCK_SIG_NAME, 1, pins.PinDirectionOutput),
				pins.NewPinDef(RESET_SIG_NAME, 1, pins.PinDirectionOutput),
			},
			IsOptional: false,
			Enable:     true,
		},
		ClockFrequency:           500000000, // 50MHz
		ResetRemainingClockTimes: 1,
	}

	RegisterDev(config)
}

type SocGlobal struct {
	*DeviceBase
	ClockFrequency           uint64
	ResetRemainingClockTimes int
	clockTimes               int
	clkState                 bool
}

func NewSocGlobal(config *SocGlobalConfig) *SocGlobal {
	return &SocGlobal{
		DeviceBase: &DeviceBase{
			Config: config,
		},
		ClockFrequency:           config.ClockFrequency,
		ResetRemainingClockTimes: config.ResetRemainingClockTimes,
	}
}

func (sg *SocGlobal) Start(ctx context.Context) error {
	sg.SetPinBool(RESET_SIG_NAME, false)
	sg.SetPinBool(CLOCK_SIG_NAME, false)
	sg.clockTimes = 0
	sg.clkState = false
	GlobalInfoInstance.ClockFrequency = sg.ClockFrequency
	GlobalInfoInstance.ResetState = false
	// go timer.StartTimer(time.Second / time.Duration(sg.ClockFrequency*2))
	return nil
}

func (sg *SocGlobal) Run(ctx context.Context) {
	if (sg.clockTimes / 2) >= sg.ResetRemainingClockTimes {
		sg.SetPinBool(RESET_SIG_NAME, true)
		GlobalInfoInstance.ResetState = true
	}
	sg.clockTimes++
	sg.SetPinBool(CLOCK_SIG_NAME, sg.clkState)
	sg.clkState = !sg.clkState
}
